import express from 'express'                    // ts中使用 express 需安装 声明文件 npm i @types/express -D
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()

const app = express()
const port: number = 3000


app.use(express.json())

//关联查找
app.get('/user/all', async (req, res) => {
    // const data = await prisma.user.findMany()
    const data = await prisma.user.findMany({
        include: {          // 相当于连表查询了
            posts: true
        }
    })
    res.send(data)
})
//单个查找
app.get('/user/single/:id', async (req, res) => {
    const row =  await prisma.user.findMany({
        where: {
            id: Number(req.params.id)   // 严格类型，数字转一下
        }
    })
    res.send(row)
})
//新增
app.post('/user/create', async (req, res) => {
    const { name, email } = req.body
    const data = await prisma.user.create({
        data: {
            name,
            email,
            posts: {
                // create: {
                //     title: '标题',
                //     publish: true
                // },
                create: [   // 关联添加 添加多条的话就是数组
                    {
                        title: '标题11',
                        content: '内容11',
                        publish: false
                    },
                    {
                        title: '标题22',
                        content: '内容22',
                        publish: true
                    }
                ],
            }
        }
    })
    res.send(data)
})

//更新
app.post('/user/update', async (req, res) => {
    const { id, name, email } = req.body
    const data = await prisma.user.update({
        where: {
            id: Number(id)
        },
        data: {
            name,
            email
        }
    })
    res.send(data)
})

//删除
app.post('/user/delete', async (req, res) => {
    const { id } = req.body
    await prisma.post.deleteMany({   // 级联删除
        where: {
            authorId: Number(id)
        }
    })
    const data = await prisma.user.delete({   // 要删除这个必须先删除关联的子表中的数据
        where: {
            id: Number(id),
        },
    })
    res.send(data)
})

app.listen(port, () => {
    console.log(`App listening on port ${port}`)
})